package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired(required = false)
    private UserMapper userMapper;


    /**
     * 用户登录
     *
     * @param phone
     * @param code
     * @param validateCode
     */
    @Override
    public R<User> login(String phone, String code, String validateCode) {

        if (!code.equals(validateCode)||validateCode == null){
            return R.error("验证码错误");
        }
        //验证码匹配，查询数据库中是否有此用户
        User loginUser = userMapper.findUserByPhone(phone);
        if (loginUser ==null){
            //数据库中没有这个用户，给他自动注册
            loginUser = new User();

            loginUser.setSex("男");
            loginUser.setPhone(phone);
            loginUser.setStatus(1);
            if (userMapper.addUser(loginUser)<=0){
                throw new CustomException("用户注册失败");
            }

        }
        return R.success(loginUser);


    }
}
